# https://zscqj.hubei.gov.cn/bsfwbs/hbszwfww/fwjgml1/
import os
import subprocess
from functools import partial
from loguru import logger

subprocess.Popen = partial(subprocess.Popen, encoding='utf-8')

import requests
from lxml import etree
import execjs

DIR_PATH = os.path.dirname(os.path.abspath(__file__))

request_session = requests.Session()
request_session.headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Pragma": "no-cache",
    "Referer": "https://zscqj.hubei.gov.cn/bsfwbs/hbszwfww/fwjgml1/",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}
cookies = {
}
request_session.cookies.update(cookies)

# html页面
url = "https://zscqj.hubei.gov.cn/bsfwbs/hbszwfww/fwjgml1/"
server_cookie_name = '97badf5c3a4a8634dd'
js_cookie_name = '924omrTVcFchP'


def get_code():
    response = request_session.get(url)
    print(response)  # 412
    if response.cookies:
        cookies[server_cookie_name] = response.cookies[server_cookie_name]
        request_session.cookies.update(cookies)
    html = etree.HTML(response.text)
    meta_content = html.xpath('//meta[2]/@content')[0]
    js_code = html.xpath('//script[@r="m" and position()=1]/text()')[0]

    return meta_content, js_code


meta_content, js_code = get_code()

with open(os.path.join(DIR_PATH, "湖北知识产权局.js"), 'r', encoding='utf-8') as js_file:
    js_text = js_file.read()
    js_text = js_text.replace('meta_content123', meta_content)
    js_text = js_text.replace("'js_code'", js_code)

js = execjs.compile(js_text)
result = js.call('main')
f80t = result.split('=', maxsplit=1)[1].split('; path')[0]
logger.success(f"{js_cookie_name}长度：{len(f80t)}  值：【{f80t}】")  # 300
cookies[js_cookie_name] = f80t
request_session.cookies.update(cookies)

url = 'https://zscqj.hubei.gov.cn/bsfwbs/hbszwfww/fwjgml1/list.json'
url = js.call('getUrl', url)
logger.success(url)

response = request_session.get(url)
response.encoding = 'utf-8'
print(response.text)
logger.info(response)
